import type { CoffeeMakerController } from './definition'
import type { Worker } from '@/controller/base/types/worker'
import type { Remote } from '@/controller/base/types/remote'
import { useWorker, useRemote, wrapSafeActions } from '@/controller/base/index'
import { RemoteTypes } from '@/controller/base/remote'
import { createBaseState, BaseGetters, BaseActions, createBaseApplianceControl } from '../BaseAppliance'
import { defineStore } from 'pinia'
import { ProgramActions, useProgramEffects } from '../common/Program/program'
import i18n from '@/i18n'
import {
  createPowerOutageState,
  PowerOutageGetters,
  PowerOutageActions,
  usePowerOutageEffects,
} from '../common/PowerOutage/powerOutage'
import {
  ACTIVE_PROGRAM,
  BSH_COMMON_COMMAND_CLEANINGMODES_APPLIANCEONRINSING,
  BSH_COMMON_COMMAND_CLEANINGMODES_PREFIX,
  COFFEE_BEAN_CONTAINER_SELECTION,
  COFFEE_CLEAN_BRWEING_UNIT,
  COFFEE_DEVICE_SHOULD_BE_CALCN_CLEANED,
  COFFEE_DEVICE_SHOULD_BE_CLEANED,
  COFFEE_DRIP_TRAY_FULL,
  COFFEE_MULTIPLE_BEVERAGES,
  COFFEE_NOT_ENOUGH_WATER_FOR_THIS_KIND_OF_BEVERAGE,
  COFFEE_WATER_TANK_EMPTY,
  COFFEE_WATER_TANK_NEARLY_EMPTY,
  OPERATION_STATES,
  PRESENT,
} from '@/constants/Command'
import { CacheTypes, getApplianceCache } from '@/controller/base/cacheHelper'
import type { ApplianceProgram } from '@/types/appliance'
import { useControlState } from '@/controller/BaseAppliance/useControl'
import { showErrorNativeModal } from '../common/ErrorHandler/errorNotice'
import { ProgramNotWritable } from '@/constants/ErrorNoticeActions'

/**
 * 饮料
 */
const BEVERAGE = 'ConsumerProducts.CoffeeMaker.Program.Beverage'
/**
 * 世界咖啡
 */
const COFFEEWORLD = 'ConsumerProducts.CoffeeMaker.Program.CoffeeWorld'
/**
 * My Coffee
 */
const MYCOFFEE = 'ConsumerProducts.CoffeeMaker.Program.MyCoffee'
/**
 * 清洁
 */
const CLEANING = 'ConsumerProducts.CoffeeMaker.Program.CleaningModes'

/**
 * 初始化数据
 */
export const createCoffeeMakerState: () => CoffeeMakerController.State = () => ({
  ...createBaseState(),
  ...createPowerOutageState(),
  usingHistoryPrograms: true,
  switchBean: '', //豆仓选择
  isDouble: false, //是否双杯
  gotoApplianceToViewError: false, // 通知前往家电端查看
})
export const CoffeeMakerGetters: CoffeeMakerController.Getters = {
  ...BaseGetters,
  ...PowerOutageGetters,
  programGroupsConfig: () => [
    {
      key: BEVERAGE,
      name: i18n.global.t('Appliance.ProgramGroup.CoffeeMaker.Beverage.Text'),
    },
    {
      key: COFFEEWORLD,
      name: i18n.global.t('Appliance.ProgramGroup.CoffeeMaker.CoffeeWorld.Text'),
    },
    {
      key: CLEANING,
      name: i18n.global.t('Appliance.ProgramGroup.CoffeeMaker.CleaningModes.Text'),
    },
  ],
  customizedAllPrograms(store) {
    // 当前为开机清洁模式 取缓存数据显示
    if (this.isStartupCleaning) {
      const cacheData = getApplianceCache({
        type: CacheTypes.AllPrograms,
        haId: store._datasource.haId,
      }) as ApplianceProgram.Scope[]
      return cacheData || []
    } else {
      return this.allPrograms || []
    }
  },
  // 是否强制隐藏暂停程序按钮
  hidePauseForced() {
    return true
  },
  // 当前为清洁程序
  isCleaningProgram() {
    return this.currentProgramKey.startsWith(BSH_COMMON_COMMAND_CLEANINGMODES_PREFIX)
  },
  // 当前为开机清洁模式
  isStartupCleaning() {
    return (
      this.operationState === OPERATION_STATES.RUN &&
      this.currentProgramKey === BSH_COMMON_COMMAND_CLEANINGMODES_APPLIANCEONRINSING
    )
  },
  // 需要忽略的调节参数Key
  customIgnoredOptionKeys() {
    return [COFFEE_MULTIPLE_BEVERAGES, COFFEE_BEAN_CONTAINER_SELECTION]
  },
  runAvailableDisabled() {
    return true
  },
  runSelectedDisabled() {
    return true
  },
}
export const CoffeeMakerActions: CoffeeMakerController.Actions = wrapSafeActions<
  CoffeeMakerController.Store,
  CoffeeMakerController.Actions
>({
  ...BaseActions,
  ...PowerOutageActions,

  // 前置错误检查
  specialAccessableCheck() {
    // 启动程序报错
    if (this.gotoApplianceToViewError) {
      showCoffeeMakerStartProgramErrorModal()
      return false
    }

    return true
  },
  // 报错错误处理
  async specialErrorInterceptor(errorData) {
    if (errorData.key === ProgramNotWritable && this.gotoApplianceToViewError) {
      showCoffeeMakerStartProgramErrorModal()
      return true
    }
    return false
  },
})

/**
 * 组合API
 */
const useStore = defineStore<
  'CoffeeMaker',
  CoffeeMakerController.State,
  CoffeeMakerController.Getters,
  CoffeeMakerController.Actions
>('CoffeeMaker', {
  state: createCoffeeMakerState,
  getters: CoffeeMakerGetters,
  actions: CoffeeMakerActions,
})

// 组件使用
export function useCoffeeMakerControl(): CoffeeMakerController.Control {
  const store = useStore() as CoffeeMakerController.Store
  const worker = useWorker(store) as Worker.ApplianceWorker<CoffeeMakerController.Store>
  const remote = useRemote(store) as Remote.ApplianceRemote<CoffeeMakerController.Store>
  return { store, worker, remote }
}

// 页面使用
export function createCoffeeMakerControl(
  control: CoffeeMakerController.Control = useCoffeeMakerControl()
): CoffeeMakerController.Control {
  const { store, worker, remote } = control

  createBaseApplianceControl(control, { remoteType: RemoteTypes.Inhouse })
  const { showControlView } = useControlState(control)

  worker.onLoad(async () => {
    const tasks: Promise<void>[] = [
      // 加载状态
      remote.loadAllStatus(),
      remote.loadAllSetting(),
      remote.loadAllEvents(),
    ]
    // 显示详情页程序列表时 调用程序列表接口
    if (showControlView.value) {
      tasks.push(store.loadAllPrograms())
    }
    await Promise.all(tasks)
    await store.loadPowerSetting()
  })

  useProgramEffects(control)
  // 电源控制 断电命令
  usePowerOutageEffects(control)

  useCoffeeMakerEffects(control)

  return control
}

function useCoffeeMakerEffects(control: CoffeeMakerController.Control) {
  const { store } = control

  useCoffeeMakerBinding(control)
  watch(
    () => store.isStartupCleaning,
    (isStartupCleaning) => {
      if (!isStartupCleaning) {
        store.loadAllPrograms()
      }
    }
  )
}
function useCoffeeMakerBinding(control: CoffeeMakerController.Control) {
  const { worker } = control

  worker.useGetValueBinding('switchBean', {
    key: COFFEE_BEAN_CONTAINER_SELECTION,
    from: 'detailOption',
  })
  worker.useGetValueBinding('currentProgramKey', {
    key: ACTIVE_PROGRAM,
    from: 'event',
    useMessage: 'only',
    patcher(patchState, reference) {
      patchState.currentProgramKey = (reference.value as string | undefined) || ''
    },
  })

  worker.useGetValueBinding('isDouble', {
    key: COFFEE_MULTIPLE_BEVERAGES,
    from: 'detailOption',
  })
  ;[
    // 水箱空
    COFFEE_WATER_TANK_EMPTY,
    // 水箱几乎为空
    COFFEE_WATER_TANK_NEARLY_EMPTY,
    COFFEE_NOT_ENOUGH_WATER_FOR_THIS_KIND_OF_BEVERAGE,
    // 滴水盘已满
    COFFEE_DRIP_TRAY_FULL,
    // 设备需要清洁
    COFFEE_DEVICE_SHOULD_BE_CLEANED,
    COFFEE_DEVICE_SHOULD_BE_CALCN_CLEANED,
    COFFEE_CLEAN_BRWEING_UNIT,
  ].forEach((key) => {
    worker.useEqualValueBinding('gotoApplianceToViewError', {
      key,
      value: PRESENT,
      from: 'event',
    })
  })
}

// 启动程序报错
export function showCoffeeMakerStartProgramErrorModal() {
  return showErrorNativeModal({
    content: i18n.global.t('Appliance.ErrorHandler.CoffeeMaker.StartProgramFailed.Text'),
  })
}
